package com.itsu.application.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.itsu.application.entity.User;
import com.mysql.jdbc.StringUtils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;

public class UserDao {

	public List<User> selectUsers(User user) throws SQLException {
		if (user == null) {
			return null;
		}
		Entity entity = Entity.create("tb_user");
		if (StrUtil.isNotBlank(user.getAdminTag())) {
			entity.set("admin_tag", user.getAdminTag());
		}
		if (StrUtil.isNotBlank(user.getPassword())) {
			entity.set("password", user.getPassword());
		}
		if (StrUtil.isNotBlank(user.getUserId())) {
			entity.set("user_id", user.getUserId());
		}
		if (StrUtil.isNotBlank(user.getUserName())) {
			entity.set("user_name", user.getUserName());
		}

		List<Entity> entities = Db.use().findAll(entity);
		List<User> users = new ArrayList<>();
		entities.forEach(x -> {
			User u = new User();
			u.setUserId(x.getStr("user_id"));
			u.setPassword(x.getStr("password"));
			u.setUserName(x.getStr("user_name"));
			u.setAdminTag(x.getStr("admin_tag"));
			users.add(u);
		});

		return users;
	}

	public List<User> selectUsersBySql(String sql, Object... params) throws SQLException {
		if (StrUtil.isBlank(sql)) {
			return null;
		}
		List<Entity> entities = Db.use().query(sql, params);
		List<User> users = new ArrayList<>();
		entities.forEach(x -> {
			User u = new User();
			u.setUserId(x.getStr("user_id"));
			u.setPassword(x.getStr("password"));
			u.setUserName(x.getStr("user_name"));
			u.setAdminTag(x.getStr("admin_tag"));
			users.add(u);
		});

		return users;
	}
}
